package com.example.music_impl.model;

import com.example.music_api.bean.AudioInfo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import cc.common.net.HttpManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 负责从网络抓取歌曲列表。
 */
public class MusicApiModel {
    public Observable<List<AudioInfo>> getAudioList() {
        return Observable.create(new ObservableOnSubscribe<List<AudioInfo>>() {
            @Override
            public void subscribe(ObservableEmitter<List<AudioInfo>> emitter) throws Exception {
                Response response = HttpManager.getInstance().getOkHttpClient().newCall(new Request.Builder()
                        .method("GET", null).url("http://music.taihe.com/top/dayhot").build()).execute();
                String xml = null;
                if (response.body() != null) {
                    xml = response.body().string();
                }
                if (xml != null) {
                    Document rootDoc = Jsoup.parse(xml);
                    List<Element> songs = rootDoc.getElementsByClass("song-title");
                    List<AudioInfo> audioInfos = new ArrayList<>();
                    for (Element e : songs) {
                        AudioInfo audioInfo = new AudioInfo();
                        Elements elements = e.getElementsByTag("a");
                        String name = ((TextNode) elements.get(0).childNode(0)).text();
                        String artist = elements.get(0).attr("title");
                        String url = elements.get(0).attr("href");
                        audioInfo.setArtist(artist);
                        audioInfo.setUrl("http://music.taihe.com" + url);
                        audioInfo.setName(name);
                        audioInfos.add(audioInfo);
                    }
                    emitter.onNext(audioInfos);
                    emitter.onComplete();
                }
            }
        });
    }
}
